package com.zbkj.service.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.zbkj.common.exception.AppException;
import com.zbkj.common.model.system.SystemGroup;
import com.zbkj.common.model.system.SystemGroupData;
import com.zbkj.common.request.PageParamRequest;
import com.zbkj.common.request.SystemGroupRequest;
import com.zbkj.common.request.SystemGroupSearchRequest;
import com.zbkj.common.result.CommonResultCode;
import com.zbkj.service.dao.SystemGroupDao;
import com.zbkj.service.service.SystemGroupDataService;
import com.zbkj.service.service.SystemGroupService;
import com.zbkj.service.util.BrandUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * SystemGroupServiceImpl 接口实现
 +----------------------------------------------------------------------
 */
@Service
public class SystemGroupServiceImpl extends ServiceImpl<SystemGroupDao, SystemGroup> implements SystemGroupService {

    @Resource
    private SystemGroupDao dao;

    @Autowired
    private SystemGroupDataService systemGroupDataService;

    @Autowired
    private TransactionTemplate transactionTemplate;

    /**
     * 列表
     *
     * @param request          请求参数
     * @param pageParamRequest 分页类参数
     * @return List<SystemGroup>
     */
    @Override
    public List<SystemGroup> getList(SystemGroupSearchRequest request, PageParamRequest pageParamRequest) {
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());

        //带 SystemGroup 类的多条件查询
        LambdaQueryWrapper<SystemGroup> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(request.getKeywords())) {
            String keywords = URLUtil.decode(request.getKeywords());
            lambdaQueryWrapper.like(SystemGroup::getName, keywords);
        }
        lambdaQueryWrapper.eq(SystemGroup::getBrandId, BrandUtil.getBrandIdByUrl());
        lambdaQueryWrapper.orderByDesc(SystemGroup::getId);
        return dao.selectList(lambdaQueryWrapper);
    }

    /**
     * 新增组合数据
     *
     * @param systemGroupRequest 新增参数
     */
    @Override
    public Boolean add(SystemGroupRequest systemGroupRequest) {
        SystemGroup systemGroup = new SystemGroup();
        BeanUtils.copyProperties(systemGroupRequest, systemGroup);
        systemGroup.setBrandId(BrandUtil.getBrandIdByUrl());
        boolean save = save(systemGroup);
        if (save) {
            systemGroup.setSourceId(systemGroup.getId());
            updateById(systemGroup);
        }
        return save;
    }

    /**
     * 删除组合数据表
     *
     * @param id Integer
     */
    @Override
    public Boolean delete(Integer id) {
        return removeById(id);
    }

    /**
     * 修改组合数据表
     *
     * @param id                 integer id
     * @param systemGroupRequest 修改参数
     */
    @Override
    public Boolean edit(Integer id, SystemGroupRequest systemGroupRequest) {
        SystemGroup systemGroup = new SystemGroup();
        BeanUtils.copyProperties(systemGroupRequest, systemGroup);
        systemGroup.setId(id);
        return updateById(systemGroup);
    }

    @Override
    public Boolean copyDefault(Integer brandId) {
        checkExists(brandId);
        LambdaQueryWrapper<SystemGroup> lqw = Wrappers.lambdaQuery();
        lqw.eq(SystemGroup::getBrandId, 0);
        lqw.orderByAsc(SystemGroup::getId);
        List<SystemGroup> systemGroups = dao.selectList(lqw);
        transactionTemplate.execute(e -> {
            systemGroups.stream().forEach(systemGroup -> {
                SystemGroup group = new SystemGroup();
                BeanUtils.copyProperties(systemGroup, group);
                group.setId(null);
                group.setCreateTime(null);
                group.setUpdateTime(null);
                group.setBrandId(brandId);
                group.setSourceId(systemGroup.getId());
                this.save(group);
                // 保存明细
                List<SystemGroupData> list = systemGroupDataService.getDefaultListByGid(systemGroup.getId());
                List<SystemGroupData> groupDataList = new ArrayList<>();
                if (CollUtil.isNotEmpty(list)) {
                    list.stream().forEach(groupData -> {
                        SystemGroupData groupDataTmp = new SystemGroupData();
                        BeanUtils.copyProperties(groupData, groupDataTmp);
                        groupDataTmp.setId(null);
                        groupDataTmp.setCreateTime(null);
                        groupDataTmp.setUpdateTime(null);
                        groupDataTmp.setGdId(group.getId());
                        groupDataTmp.setBrandId(brandId);
                        groupDataList.add(groupDataTmp);
                    });
                }
                // 招商邀约/活动邀约
                if(systemGroup.getId().equals(5)){
                    SystemGroupData groupDataTmp = new SystemGroupData();
                    groupDataTmp.setId(null);
                    groupDataTmp.setCreateTime(null);
                    groupDataTmp.setUpdateTime(null);
                    groupDataTmp.setGdId(group.getId());
                    groupDataTmp.setBrandId(brandId);
                    groupDataTmp.setSort(13);
                    groupDataTmp.setStatus(true);
                    groupDataTmp.setGid(systemGroup.getId());
                    groupDataTmp.setValue("{\"id\":89,\"sort\":13,\"fields\":[{\"name\":\"wap_url\",\"title\":\"wap_url\",\"value\":\"/pages/users/user_vip/index\"},{\"name\":\"name\",\"title\":\"name\",\"value\":\"活动邀约\"},{\"name\":\"pic\",\"title\":\"pic\",\"value\":\"crmebimage/public/content/2025/08/08/60e9b943eabe495f86544b3726dd322f1arcngoshv.png\"},{\"name\":\"url\",\"title\":\"url\",\"value\":\"/pages/users/yiQiXiu/list\"},{\"name\":\"info\",\"title\":\"info\",\"value\":\"\"}],\"status\":true}");

                    groupDataList.add(groupDataTmp);
                }
                if (CollUtil.isNotEmpty(groupDataList)) {
                    systemGroupDataService.saveBatch(groupDataList);
                }
            });
            return true;
        });
        return true;
    }

    @Override
    public Integer getGdIdByGId(Integer gid) {
        // 取对应的品牌商的数据组id
        LambdaQueryWrapper<SystemGroup> lqw = Wrappers.lambdaQuery();
        lqw.eq(SystemGroup::getSourceId, gid);
        lqw.eq(SystemGroup::getBrandId, BrandUtil.getBrandIdByUrl());
        SystemGroup systemGroup = getOne(lqw);
        if (ObjectUtil.isNotNull(systemGroup)) {
            return systemGroup.getId();
        }
        return null;
    }

    @Override
    public boolean getNotExists(Integer brandId) {
        LambdaQueryWrapper<SystemGroup> lqw = Wrappers.lambdaQuery();
        lqw.eq(SystemGroup::getBrandId, brandId);
        return count(lqw) <= 0;
    }

    private void checkExists(Integer brandId) {
        if (!getNotExists(brandId)) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "当前品牌商下已存在表单数据");
        }
    }

}

